import ADVM from "../../ADCore/MVVM/ADVM";
import ADQ from "../../ADCore/Core/ADQ";
import { IProgressManager } from "../../ADCore/Interfaces/IGameManager";
import { ui } from "../../ui/layaMaxUI";

/**
 * 加载页
 */
export default class LoadingPageView extends ui.StartGameUI {
  dataContext: ADVM;
  progress: IProgressManager;

  static curLoading: LoadingPageView;

  /**
   * 弹出加载页面
   * @param caller 作用域
   * @param compelet 完成加载监听
   */
  static showPage(caller, compelet, pageCompelet): LoadingPageView {
    var loading = new LoadingPageView();
    loading.compeletEvent = Laya.Handler.create(caller, compelet);
    loading.pageCompeletEvent = Laya.Handler.create(caller, pageCompelet);
    this.curLoading = loading;
    loading.open();
    return loading;
  }

  static closeLoading() {
    LoadingPageView.curLoading.close();
  }
  private compeletEvent: Laya.Handler;
  private pageCompeletEvent: Laya.Handler;
  constructor() {
    super();

    this.progress = ADQ.getProgressManager(null, 0);
    this.progress.bindProgress(this.realProgeass, this);
  }
  onAwake() {
    ADQ.adaptive.sceneAdaptive(this);
    this.bindVMData();
    this.pageCompeletEvent.run();
  }
  compeletProgress() {
    this.compeletEvent.run();
    this.close();
  }
  realProgeass(cur) {
    this.dataContext["progress"] = cur;
  }
  bindVMData() {
    console.debug("加载页加载完毕......");
    var self = this;
    var options = {
      el: this,
      data: {
        initWidth: 0,
        maxProgress: 0,
        progress: 0,
        progressText: 0,
      },
      watch: {
        progress: function (value, old, node: Laya.Sprite) {
          if (this.initWidth == 0) {
            this.initWidth = node.width;
            node.width = 1;
          }
          if (self.progress.max == 0) return value;
          var progressRate = value / self.progress.max;
          Laya.Tween.to(this, { progressText: progressRate }, 300);
          var w = this.initWidth * progressRate;

          if (progressRate >= 1) {
            Laya.Tween.to(
              node,
              { width: w },
              300,
              null,
              Laya.Handler.create(self, () => {
                Laya.Handler.create(self, self.compeletProgress).run();
                self.destroy();
              })
            );
          } else {
            Laya.Tween.to(node, { width: w }, 300);
          }
          return value;
        },
        progressText: function (value: number, old, node: Laya.Text) {
          return (value * 100).toFixed(2) + "%";
        },
      },
      methods: {},
    };
    this.dataContext = new ADVM(options);
  }
}
